package com.ibo.htlivecamera.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.ibo.htlivecamera.R;
import com.ibo.htlivecamera.util.Downloader;
import com.ibo.htlivecamera.util.InstallUtil;

import java.io.File;

public class UpdateDialog extends Dialog implements Downloader.DownloadListener {

    private ProgressBar pr;
    private File file;
    private Downloader mDownloader;

    public UpdateDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_dialog);
        pr = (ProgressBar) findViewById(R.id.pr);


    }

    public void startDownload(String url) {
        System.out.println("#######    开始下载:  "+url);

        file = new File(getContext().getFilesDir() + "/update.apk");
        if (file.exists()) {
            file.delete();
        }
        mDownloader = new Downloader(file, this);
        mDownloader.execute(url);
    }

    @Override
    public void onProgressUpdate(int progress) {
        pr.setProgress(progress);
    }

    @Override
    public void downloadCompleted(boolean isSuccess) {
        if (isSuccess) {
            Toast.makeText(getContext(), "下载成功，请用遥控器按[安装]按钮！", Toast.LENGTH_LONG).show();
            install();
            dismiss();
        } else {
            pr.setProgress(0);
            dismiss();
            showToast("下载失败!");
        }
    }

    private void install() {
        if (file.exists()) {
            InstallUtil.install(getContext(), file);
            dismiss();
        } else {
            showToast("安装失败!");
        }
    }

    private void showToast(String s) {
        Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void downloadCancel() {

    }
}
